package com.sc.site.member;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.sc.dal.common.pagination.Page;
import com.sc.dal.common.pagination.PaginationBean;
import com.sc.dal.dto.member.MemberCardDto;
import com.sc.dal.mapper.member.MemberCardMapper;
import com.sc.dal.model.member.BankInst;
import com.sc.dal.model.member.Member;
import com.sc.dal.model.member.MemberCard;
import com.sc.service.member.BankInstService;
import com.sc.service.member.MemberCardService;
import com.sc.site.BaseController;
import com.sc.util.ChanPay.util.BankCodeNameEnum;
import com.sc.util.ChanPay.util.BankUtil;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Common;
import com.sc.util.data.Constants;
import com.sc.util.data.DataUtil;
import com.sc.util.data.JudgeUtil;
import com.sc.util.data.SessionContainer;
import com.sc.util.exception.ExceptionEnum;
/**
 * @ClassName: AppMemberCardController
 * @Description: 用户银行卡管理
 * @author LeiJia
 * @date 2017年3月203日下午16：45:44
 * @version V1.0
 */
@RequestMapping("/card")
@Controller
public class MemberCardController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
		
	@Autowired
	private MemberCardService memberCardService;
	
	@Autowired
	private BankInstService  bankInstService;
	
	/**
	 * @Title: cardIsBelongsTheBank
	 * @Description 3.根据银行卡号判断是否是所选择的的开户银行的卡
	 * @param param
	 * @date 2017年3月20日下午14:50:15
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value ="cardIsBelongsTheBank",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> card_cardIsBelongsTheBank(String cardNumber,String bankName){
		Map<String, Object> resultMap=new LinkedHashMap<String, Object>();
		try{
           
            if(Common.isEmpty(bankName)){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_BANK_NAME_ERROR);
    			return resultMap;
            }
            if(Common.isEmpty(cardNumber)){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_NUMBER_ERROR);
    			return resultMap;
            }
            String card_name = BankUtil.getNameOfBank(cardNumber); 
            if(JudgeUtil.isHave(card_name, bankName)){
            	resultMap.put("cardIsBelongsTheBank",true);
            }else{
            	resultMap.put("cardIsBelongsTheBank",false);
            }
            //根据银行卡号查询是否保存过该银行卡
            MemberCard mcard = memberCardService.selectByCardNumber(cardNumber);
            if(mcard != null){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_HAS_EXIST_SUCCESS);
    			return resultMap;
            }
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_ISBLANGTHEBANK_QUERY_FAIL);
			logger.info("判断银行卡所属银行异常!");
		}
		return resultMap;
	}
	/**
	 * @Title: addMemberCard
	 * @Description 添加银行卡号和修改银行卡信息
	 * @param param
	 * @date 2017年3月20日下午14:50:15
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value ="addMemberCard",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> card_addMemberCard(MemberCard card ,HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> resultMap=new LinkedHashMap<String, Object>();
		try{ 
			Member member = SessionContainer.getSessionMember(request);
			if(member == null){
				resultMap.put("sessionValid", true); //会话失效
				return resultMap;
			}
			card.setMemberId(member.getmId());
            if(Common.isEmpty(card.getMemberId())){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
    			return resultMap;
            }
            if(Common.isEmpty(card.getRealName())){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_REAL_NAME_ERROR);
    			return resultMap;
            }
            if(Common.isEmpty(card.getIdNumber())){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_ID_NUMBER_ERROR);
    			return resultMap;
            }
            if(Common.isEmpty(card.getBankName())){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_BANK_NAME_ERROR);
    			return resultMap;
            }
            if(Common.isEmpty(card.getCardNumber())){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_NUMBER_ERROR);
    			return resultMap;
            }
            if(Common.isEmpty(card.getPhone())){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_PHONE_NUMBER_ERROR);
    			return resultMap;
            }
            
            //首先校验输入银行卡号是否属于所选开户银行
            String card_name = BankUtil.getNameOfBank(card.getCardNumber());
            if(JudgeUtil.isHave(card_name, card.getBankName())){
            	card.setCardName(card_name);
            }else{
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_NUMBER_NOT_MATCH_SUCCESS);
    			return resultMap;
            }
            if(card.getId() == null){
                //根据银行卡号查询是否保存过该银行卡
                MemberCard mcard = memberCardService.selectByCardNumber(card.getCardNumber());
                if(mcard != null){
        			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_BANK_CARD_HAS_EXIST_SUCCESS);
        			return resultMap;
                }
            }
            card.setInstCode(BankCodeNameEnum.getInstNameByCode(card.getBankName()));
            card.setModifier(card.getMemberId());
            card.setModifyDate(new Date());
            card.setIsDelete(Constants.IS_DELETEA);
            
            int inserMemberCardResult = 0 ; 
            if(card.getId() == null){
                card.setCreateDate(new Date());
                card.setCreater(card.getMemberId());
                inserMemberCardResult =  memberCardService.insert(card);
            }else{
                inserMemberCardResult =  memberCardService.updateByPrimaryKeySelective(card);
            }
            if(inserMemberCardResult == 0){
    			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
    			return resultMap;
            }
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
			logger.info("添加银行卡号异常!");
		}
		return resultMap;
	}
	/**
	 * @Title: bankCardList
	 * @Description 查询开户银行卡列表
	 * @date 2017年3月29日上午10:37:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="bankCardList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> bankCardList(){
		Map<String,Object> resultMap= new LinkedHashMap<String, Object>();
		List<BankInst> instList = null;
		try{
			 BankInst inst = new BankInst();
			 inst.setCardAttribute(Constants.ChanQPayInst.CARD_ATTRIBUTE_PRIVATE); //对公/对私：B/C
			 inst.setCardType(Constants.ChanQPayInst.CARD_TYPE_DC); //卡类型 贷记=CC，借记=DC，综合=GC
			 inst.setPayMode(Constants.ChanQPayInst.PAY_MODE_QPAY); //支付模式ONLINE_BANK(网银支付)；QPAY(快捷支付)；POS（pos支付）
			 
			 instList = bankInstService.selectAllBankInst(inst);
  		     DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS); 
  			 resultMap.put("data",instList );		
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_FAIL);
			
		}
		return resultMap;
	}
	/**
	 * @Title: memberCardsList
	 * @Description 查询用户银行卡列表
	 * @param currPage
	 * @param pageSize
	 * @param memberId 
	 * @date 2017年3月20日下午14:34:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value ="memberCardsList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> card_memberCardsList(String memberId){
		Map<String, Object> resultMap=new LinkedHashMap<String, Object>();
		List<MemberCard> resultList = new ArrayList<MemberCard>();
		try{
			if(Common.isEmpty(memberId)){				
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			MemberCard card = new MemberCard();
			card.setMemberId(memberId);			
			resultList = memberCardService.selectByParam(card);	
		    if(resultList != null && resultList.size() >0){
		    	for(MemberCard c : resultList){
		    		if(Common.isNotEmpty(c.getPicture())){
			    		c.setPicture(ConfigBeanAdapter.fileAccessAddress+c.getPicture());
		    		}
		    	}
		    }
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.info("分页查询银行卡列表异常!");
		}
		resultMap.put("data", resultList);
		return resultMap;
	}
	/**
	 * @Title: memberCardsList
	 * @Description 查询用户银行卡列表
	 * @param currPage
	 * @param pageSize
	 * @param memberId 
	 * @date 2017年3月20日下午14:34:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value ="card_memberCardsListPage",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> card_memberCardsListPage(Integer currPage,Integer pageSize,String memberId){
		Map<String, Object> resultMap=new LinkedHashMap<String, Object>();
		List<MemberCard> resultList = new ArrayList<MemberCard>();
		int totalRecords = 0;
		int totalPage = 0;
		try{
			if(currPage == null || pageSize == null || Common.isEmpty(memberId)){				
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			MemberCard card = new MemberCard();
			card.setMemberId(memberId);
			Page page = new Page();
			// 传入页号
			page.setCurrPage(currPage);
			// 传入每页记录数
			page.setPageSize(pageSize);
			PaginationBean<MemberCard> result = memberCardService.getPagingDatas(card,
					page, "count", "selectByParam",MemberCardMapper.class);
			resultList = result.getPageList();
			totalRecords = result.getTotalRecords();
			totalPage = result.getTotalPage();	
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.info("分页查询银行卡列表异常!");
		}
		resultMap.put("count", totalRecords);
		resultMap.put("pages", totalPage);
		resultMap.put("data", resultList);
		return resultMap;
	}
	


	/**
	 * @Title: memberBankInstList
	 * @Description 当前用户所有银行卡的银行机构列表
	 * @date 2017年4月28日下午13:32:05
	 * @author LeiJia  
	 * @return JSONObject    返回类型
	 */
	@RequestMapping(value="/memberBankInstList")
	@ResponseBody
	public JSONObject memberBankInstList(HttpServletRequest request){
		JSONObject json = new JSONObject();
		try{

			Member member = SessionContainer.getSessionMember(request);
			if(member == null){
				json.put("sessionValid", false);
				return json;
			}
			List<MemberCardDto> cardList = memberCardService.memberBankInstList(member.getmId());		
			json.put("flag", true);	
			json.put("instList", cardList);
		}catch(Exception e){
			e.printStackTrace();
			json.put("flag", false);
			return json;
		}
		return json;
	}

	/**
	 * @Title: memberBankCardList
	 * @Description 当前用户所有银行卡列表
	 * @date 2017年4月28日下午13:44:05
	 * @author LeiJia  
	 * @return JSONObject    返回类型
	 */
	@RequestMapping(value="/memberBankCardList")
	@ResponseBody
	public JSONObject memberBankCardList(HttpServletRequest request){
		JSONObject json = new JSONObject();
		try{
		//	String totalAmount = (String) request.getSession().getAttribute("totalAmount");

			Member member = SessionContainer.getSessionMember(request);
			if(member == null){
				json.put("sessionValid", false);
				return json;
			}
			String bank_name = getPara("bank_name");
			MemberCardDto cartDto = new MemberCardDto(member.getmId(), bank_name);			
			List<MemberCardDto> cardList = memberCardService.memberBankCardList(cartDto);		
			json.put("flag", true);	
			json.put("cardList", cardList);
		}catch(Exception e){
			e.printStackTrace();
			json.put("flag", false);
			return json;
		}
		return json;
	}
	/**
	 * @Title: selectCardById
	 * @Description 查询银行卡信息
	 * @date 2017年5月18日上午11:41
	 * @author LeiJia  
	 * @return JSONObject    返回类型
	 */
	@RequestMapping(value="/selectCardById")
	@ResponseBody
	public JSONObject selectCardById(HttpServletRequest request,Integer id){
		JSONObject json = new JSONObject();
		try{
		//	String totalAmount = (String) request.getSession().getAttribute("totalAmount");

			Member member = SessionContainer.getSessionMember(request);
			if(member == null){
				json.put("sessionValid", false);
				return json;
			}
			if(id == null){
				json.put("flag",false);
				return json;
			}		
			MemberCard memberCard = memberCardService.selectByPrimaryKey(id);
			json.put("flag", true);	
			json.put("memberCard", memberCard);
		}catch(Exception e){
			e.printStackTrace();
			json.put("flag", false);
			return json;
		}
		return json;
	}
	/**
	 * @Title: deleteCardById
	 * @Description 删除银行卡
	 * @date 2017年5月18日上午11:41
	 * @author LeiJia  
	 * @return JSONObject    返回类型
	 */
	@RequestMapping(value="/deleteCardById")
	@ResponseBody
	public JSONObject deleteCardById(HttpServletRequest request,MemberCard card ){
		JSONObject json = new JSONObject();
		try{
		//	String totalAmount = (String) request.getSession().getAttribute("totalAmount");

			Member member = SessionContainer.getSessionMember(request);
			if(member == null){
				json.put("sessionValid", false);
				return json;
			}
			if(card == null){
				json.put("flag",false);
				return json;
			}	
			if(card.getId() == null){
				json.put("flag",false);
				return json;
			}
			card.setIsDelete(Constants.IS_DELETEB);
			card.setModifier(member.getmId());
			card.setModifyDate(new Date());
		    int updateResult = memberCardService.updateByPrimaryKeySelective(card);
		    if(updateResult > 0){
				json.put("flag", true);		
		    }else{
				json.put("flag", false);		
		    }
		}catch(Exception e){
			e.printStackTrace();
			json.put("flag", false);
			return json;
		}
		return json;
	}
}
